package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * ━━━━━━神兽出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛Code is far away from bug with the animal protecting
 * 　　　　┃　　　┃    神兽保佑,代码无bug
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * <p>
 * ━━━━━━感觉萌萌哒━━━━━━
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate template;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        String exists = (String) operations.get(skuId.toString());

        if (StringUtils.isEmpty(exists)) {
            //购物车没有这个商品
            CartItem cartItem = new CartItem();
            //添加新商品
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1、远程查询当前要添加的商品信息
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfoVo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });

                //2、商品信息添加到购物车
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfoVo.getSkuDefaultImg());
                cartItem.setTitle(skuInfoVo.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(skuInfoVo.getPrice());
            }, executor);

            CompletableFuture<Void> getSkuInfoAttrValuesTask = CompletableFuture.runAsync(() -> {
                //3、查出sku的组合信息
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask, getSkuInfoAttrValuesTask).get();
            String s = JSON.toJSONString(cartItem);
            operations.put(skuId.toString(), s);
            return cartItem;
        } else {
            //购物车有此商品
            //增加数量
            CartItem existItem = JSON.parseObject(exists, CartItem.class);
            existItem.setCount(existItem.getCount() + num);
            String s = JSON.toJSONString(existItem);
            operations.put(skuId.toString(), s);
            return existItem;
        }
    }

    /**
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        String str = (String) operations.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(str, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        //1、登陆
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //当前已经处于登录状态
            String userKey = CART_PREFIX+userInfoTo.getUserId();
            //2、如果临时购物车的数据还没进行合并
            String tempKey = CART_PREFIX+userInfoTo.getUserKey();
            List<CartItem> temps = getCartItems(tempKey);
            if(temps!=null&&temps.size()>0){
                //临时购物车里有数据，需要合并
                for(CartItem temp:temps){
                    addToCart(temp.getSkuId(),temp.getCount());
                }
            }
            //合并完成后，清空临时购物车
            clearCart(tempKey);
            //然后再获取登陆后的购物车的数据
            List<CartItem> cartItems = getCartItems(userKey);
            cart.setCartItems(cartItems);
        } else {
            //没有登陆
            String cartkey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartkey);
            cart.setCartItems(cartItems);
        }
        return cart;
    }

    /**
     * 获取指定购物车的数据
     * @param cartkey
     * @return
     */
    private List<CartItem> getCartItems(String cartkey){
        BoundHashOperations<String, Object, Object> hashOps = template.boundHashOps(cartkey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            List<CartItem> cartItems = values.stream().map(value -> {
                String str = (String) value;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;

            }).collect(Collectors.toList());
            return cartItems;
        }else{
            return null;
        }
    }


    /**
     * 获取到我们要操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //1、当前用户的登录信息
        String cartKey = "";
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        BoundHashOperations<String, Object, Object> operations = template.boundHashOps(cartKey);
        return operations;
    }

    /**
     * 清空购物车
     * @param userKey
     */
    @Override
    public void clearCart(String userKey){
        template.delete(userKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String,Object,Object> ops = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        ops.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()==null){
            return null;
        }else{
            String cartKey = CART_PREFIX+userInfoTo.getUserId();
            List<CartItem> caartItems = getCartItems(cartKey);
            if(caartItems!=null&&caartItems.size()>0){
                List<CartItem> finalResult = caartItems.stream()
                        .filter(item->item.getCheck())
                        .map(item->{
                            //更新为最新价格(远程查询价格)
                            R r = productFeignService.getPrice(item.getSkuId());
                            item.setPrice(new BigDecimal(r.get("data").toString()));
                            return item;
                        })
                        .collect(Collectors.toList());
                return finalResult;
            }else{
                return null;
            }

        }
    }
}